/*
 * Johannes Niederl
 * 29.04.2014
 */

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>

int main(int argc, char* argv[]){
	if(argc != 3){
		printf("usage: yacp <sourcefile> <destinationfile>\n");
		return 1;
	}
	
	char* sourcepath = argv[1];
	char* destinationpath = argv[2];
	
	int sourcefile = open(sourcepath, O_RDONLY);
	
	if(sourcefile <0)
	{
		fprintf(stderr, "The sourcefile '%s' could not be opened!\n", sourcepath);
		fprintf(stderr, "%s\n", strerror(errno));
		return errno;
	}
	
	
	int destinationfile = open(destinationpath, O_CREAT | O_WRONLY | O_EXCL, 0666);
	
	if(destinationfile <0)
	{
		fprintf(stderr, "The destinationfile '%s' exists already!\n", destinationpath);
		fprintf(stderr, "%s\n", strerror(errno));
		return errno;
	}
	
	char buffer[4096];
	int readSize = 0;
	while((readSize = read(sourcefile, &buffer, 4096)) !=0)
	{
		if(readSize < 0)
		{
			fprintf(stderr, "Error while reading file '%s'!\n", sourcepath);
			fprintf(stderr, "%s\n", strerror(errno));
			return errno;
		}
		
		if(write(destinationfile, &buffer, readSize) < 0)
		{
			fprintf(stderr, "The destinationfile '%s' could not be written!\n", destinationpath);
			fprintf(stderr, "%s\n", strerror(errno));
			return errno;
		}
		
	}
	
	close(sourcefile);
	close(destinationfile);
	
	return 0;
}
